{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "name": "Automated_covid_detector.ipynb",
      "provenance": [],
      "collapsed_sections": [],
      "include_colab_link": true
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "accelerator": "GPU"
  },
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "view-in-github",
        "colab_type": "text"
      },
      "source": [
        "<a href=\"https://colab.research.google.com/github/mr7495/COVID-CT-Code/blob/master/Automated_covid_detector.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "Cq6NBm56I46q",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "# idea from https://github.com/mr7495/COVID-CT-Code\n",
        "# developer email : mr7495@yahoo.com"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "6JmhSAzXPUaX",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "!nvidia-smi #show the allocated GPU"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "5yqhPi-FS60r",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "#Connect your Google Drive \n",
        "from google.colab import drive\n",
        "drive.mount('/content/drive')"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "7UAp6XlqPeou",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "#upgrade and install essential libraries\n",
        "#Install essential libraries\n",
        "!pip install git+https://github.com/mr7495/RetinaNet"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "zw0BhQ7nPihU",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "import keras\n",
        "import numpy as np\n",
        "import cv2\n",
        "import os\n",
        "import random\n",
        "import shutil\n",
        "import pandas as pd\n",
        "import csv\n",
        "import zipfile\n",
        "from keras import optimizers\n",
        "from keras.models import Sequential,Model\n",
        "from keras.layers import Dropout, Flatten, Dense,Input\n",
        "from keras.applications.resnet_v2 import ResNet50V2\n",
        "from keras.applications.xception import Xception\n",
        "from keras.applications.resnet50 import ResNet50\n",
        "from keras.applications.vgg16 import VGG16\n",
        "from keras.callbacks import ModelCheckpoint\n",
        "from keras.applications.imagenet_utils import preprocess_input\n",
        "from keras import backend as K\n",
        "from keras.preprocessing.image import ImageDataGenerator\n",
        "from keras.initializers import RandomNormal\n",
        "import keras.backend as k\n",
        "from sklearn.utils import shuffle\n",
        "import io\n",
        "from PIL import Image as pil_image\n",
        "from keras_retinanet import layers\n",
        "import keras.backend as k\n",
        "import keras_retinanet"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "89hm-PDB0SSb",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "shape=(512,512,1) #shape of the dataset images (in TIFF format)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "3C8WeNCTRSIi",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "#Run the CT selection Algorithm\n",
        "!mkdir 'selected_data'\n",
        "data_path='path to the folder that contained the patient CT scans images'\n",
        "data_files=[]\n",
        "for r,d,f in os.walk(data_path): #add the path of the CT scan images of the patient\n",
        "  for file in f:\n",
        "    if '.tif' in file:\n",
        "      data_files.append(os.path.join(r,file)) #get the images path from the data_folder\n",
        "\n",
        "selected=[]          \n",
        "zero=[]\n",
        "names=[]\n",
        "for img_path in data_files:\n",
        "    names.append(img_path)\n",
        "    pixel=cv2.imread(img_path,cv2.IMREAD_UNCHANGED ) #read the TIFF file\n",
        "    sp=pixel[240:340,120:370] #Crop the region\n",
        "    counted_zero=0\n",
        "    for i in np.reshape(sp,(sp.shape[0]*sp.shape[1],1)):\n",
        "        if i<300: #count the number of pixel values in the region less than 300\n",
        "            counted_zero+=1\n",
        "    zero.append(counted_zero) #add the number of dark pixels of the image to the list\n",
        "min_zero=min(zero)\n",
        "max_zero=max(zero)\n",
        "threshold=(max_zero-min_zero)/1.5 #Set the threshold\n",
        "indices=np.where(np.array(zero)>threshold) #Find the images that have more dark pixels in the region than the calculated threshold\n",
        "selected_names=np.array(names)[indices] #Selected images\n",
        "\n",
        "\n",
        "for selected_img in selected_names:\n",
        "    shutil.copy(selected_img,'selected_data')"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "rRXGewOAMJ1q",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "#The fully automated patient classification network\n",
        "Path='Path to the trained models' # You can use this trained model : 'drive/My Drive/COVID-CTset/trained_networks/FPN-fold1.hdf5'\n",
        "selected_imgs_path=[]\n",
        "for r,d,f in os.walk('selected_data'): # add the path of the selected images\n",
        "  for file in f:\n",
        "    if '.tif' in file:\n",
        "      selected_imgs_path.append(os.path.join(r,file)) #get the images path from the data_folder\n",
        "\n",
        "k.clear_session() #clear keras backend\n",
        "custom_object={'UpsampleLike': keras_retinanet.layers._misc.UpsampleLike} #Upsampling layer that was used in feature pyramid network\n",
        "net=keras.models.load_model(Path, custom_objects=custom_object)\n",
        "\n",
        "\n",
        "covid_label=0 # index of COViD-19 class \n",
        "normal_label=1  # index of normal class \n",
        "normal_predicted=0\n",
        "covid_predicted=0\n",
        "for img_name in selected_imgs_path: #read images\n",
        "  img=cv2.imread(img_name,cv2.IMREAD_UNCHANGED)\n",
        "  pred_ind=np.argmax(net.predict(np.expand_dims(np.expand_dims(img,axis=0),axis=3))[0]) #predicted label\n",
        "  if pred_ind==normal_label:\n",
        "    normal_predicted+=1\n",
        "  else:\n",
        "    covid_predicted+=1\n",
        "\n",
        "all_imgs_num=len(selected_imgs_path) \n",
        "if covid_predicted>=0.1*all_imgs_num: #if at least 10% of a patient CT scans be classified as covid\n",
        "  print('The patient is identified as infected to COVID-19')\n",
        "else:\n",
        "  print('The patient is identified as normal')"
      ],
      "execution_count": 0,
      "outputs": []
    }
  ]
}
